import axios from 'axios'
import { ElMessage } from 'element-plus'
import NProgress from 'nprogress'
import { getToken, toLogin } from '~/composables/auth'
import 'nprogress/nprogress.css'

const request = axios.create({
  timeout: 60 * 1000,
})

function download(blob: Blob, fileName: string) {
  const dom = document.createElement('a')
  const url = window.URL.createObjectURL(blob)
  dom.href = url
  dom.download = decodeURI(fileName)
  dom.style.display = 'none'
  document.body.appendChild(dom)
  dom.click()
  dom.parentNode?.removeChild(dom)
  window.URL.revokeObjectURL(url)
}

request.interceptors.request.use(
  (config) => {
    NProgress.start()
    config.headers.Token = getToken()
    return config
  },
  (error) => {
    NProgress.done()
    ElMessage.error(error)
    return Promise.reject(error)
  },
)

request.interceptors.response.use(
  (response) => {
    NProgress.done()
    if (response.headers['content-type'] === 'application/vnd.ms-excel;charset=utf8') {
      // console.warn(response.headers['content-disposition'])
      const { data, headers } = response
      const fileName = (headers['content-disposition'] || '').replace(/\s+/, '').replace(/.*;filename=(.*)/, '$1')
      const blob = new Blob([data], { type: headers['content-type'] })
      download(blob, fileName)
      return response.data
    }

    const res = response.data

    if (res.code === 401) {
      // toLogin()
    }
    else if (res.code === 200) {
      return res
    }

    ElMessage.warning(res.message ?? '系统异常')
    return Promise.reject(new Error(res.message ?? '系统异常'))
  },
  (error) => {
    NProgress.done()
    ElMessage.error(error)
    return Promise.reject(error)
  },
)

export { request }
